/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socafeclient;

import entity.*;
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.font.TextAttribute;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.sound.sampled.DataLine;
import javax.swing.*;

import javax.swing.table.TableCellRenderer;

/**
 *
 * @author wakowa
 */
public class AdministracionRecetas extends javax.swing.JFrame {

    /**
     * Creates new form AdministracionRecetas
     */    
    public TableModelRecetasInsumos tableModelRecetasInsumos;
    public TableModelProductos tableModelProductos;
    public List<Tiposproductos> tipoDeProducto;
    public AdministracionRecetas() {
        tableModelRecetasInsumos = new TableModelRecetasInsumos();
        tableModelProductos = new TableModelProductos(Main.productosFacade.findAll());
        tipoDeProducto = Main.tiposproductosFacade.findAll();
        
        initComponents();
        for (Iterator i = tipoDeProducto.iterator() ; i.hasNext();)
            jComboBoxTipoProducto.addItem(((Tiposproductos)i.next()).getNombre());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldNombreProducto = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldPrecio = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBoxTipoProducto = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTestAreaModoPreparacion = new javax.swing.JTextArea();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setModel(tableModelProductos);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Nombre Producto:");

        jLabel2.setText("Precio:");

        jLabel3.setText("Tipo de producto:");

        jTable2.setModel(tableModelRecetasInsumos);
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Actualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Eliminar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setText("Modo de Preparaci�n:");

        jTestAreaModoPreparacion.setColumns(20);
        jTestAreaModoPreparacion.setRows(5);
        jScrollPane3.setViewportView(jTestAreaModoPreparacion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextFieldNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jButton3))
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 816, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 816, Short.MAX_VALUE))))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextFieldNombreProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextFieldPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBoxTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        if (jTable2.getSelectedColumn() == 0){
            tableModelRecetasInsumos.setValueAt(jTable2.getSelectedRow(), 0);
        }
    }//GEN-LAST:event_jTable2MouseClicked

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        entity.Productos p = tableModelProductos.getProductoAt(jTable1.getSelectedRow());
        tableModelRecetasInsumos.addTableModelRecetasInsumos(Main.insumosFacade.findAll(), Main.RecetasinsumosFacade.FindByID(p.getIdreceta().getIdreceta()));
        
        jTextFieldNombreProducto.setText(tableModelProductos.getValueAt(jTable1.getSelectedRow(),1).toString());
        jTextFieldPrecio.setText(tableModelProductos.getValueAt(jTable1.getSelectedRow(),2).toString());
        jComboBoxTipoProducto.setSelectedItem(tableModelProductos.getValueAt(jTable1.getSelectedRow(),3));
        jTestAreaModoPreparacion.setText( p.getIdreceta().getModoPreparacion());
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        int idReceta;
        String nombreProducto = jTextFieldNombreProducto.getText();
        Double precio = Double.parseDouble(jTextFieldPrecio.getText().toString());
        int idTipoDeProducto = ((Tiposproductos)Main.tiposproductosFacade.findByName( jComboBoxTipoProducto.getSelectedItem().toString())).getIdtipoprod();
        
        String MododePreparacion = jTestAreaModoPreparacion.getText();
        Boolean recetas = Main.recetasFacade.crearReceta(MododePreparacion);
        idReceta = Main.recetasFacade.getLastInsert();
        
        //Insertar Insumos 
        ArrayList misInsumos = tableModelRecetasInsumos.getDataList();
        
        Main.RecetasinsumosFacade.EliminarPorIdReceta(idReceta);
        for(Iterator i = misInsumos.iterator();i.hasNext();)
        {
            Object[] o = (Object[]) i.next();
            if( o[0] == Boolean.TRUE )
                Main.RecetasinsumosFacade.create(new Recetasinsumos(idReceta, Integer.parseInt(o[1].toString()), 0));
        }
        
        Boolean productoCreado = Main.productosFacade.crearProductos(nombreProducto,precio,idReceta,idTipoDeProducto);
        
        if(productoCreado)
            JOptionPane.showMessageDialog( this , "Producto agregado correcttamente");
        
          tableModelProductos.clear((List)Main.productosFacade.findAll());
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        int idReceta;        
        entity.Productos p = tableModelProductos.getProductoAt(jTable1.getSelectedRow());
        String nombreProducto = jTextFieldNombreProducto.getText();
        Double precio = Double.parseDouble(jTextFieldPrecio.getText().toString());
        int idTipoDeProducto = ((Tiposproductos)Main.tiposproductosFacade.findByName( jComboBoxTipoProducto.getSelectedItem().toString())).getIdtipoprod();
        
        String MododePreparacion = jTestAreaModoPreparacion.getText();
        idReceta = p.getIdreceta().getIdreceta();
        Recetas r  =  new Recetas();
        r.setIdreceta(idReceta );
        r.setModoPreparacion(MododePreparacion);
        
        Main.recetasFacade.edit(r);        
        
        //Insertar Insumos 
        ArrayList misInsumos = tableModelRecetasInsumos.getDataList();
        
        Main.RecetasinsumosFacade.EliminarPorIdReceta(idReceta);
        for(Iterator i = misInsumos.iterator();i.hasNext();)
        {
            Object[] o = (Object[]) i.next();
            if( o[0] == Boolean.TRUE )
                Main.RecetasinsumosFacade.create(new Recetasinsumos(idReceta,Integer.parseInt(o[1].toString()) ,0));
        }
        
        Boolean productoCreado = Main.productosFacade.crearProductos(nombreProducto,precio,idReceta,idTipoDeProducto);
        
        if(productoCreado)
            JOptionPane.showMessageDialog( this , "Producto editado correcttamente");
        
          tableModelProductos.clear((List)Main.productosFacade.findAll());

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
            
        entity.Productos p = (entity.Productos)tableModelProductos.removeProductosAt(jTable1.getSelectedRow());
        Main.productosFacade.remove(p);
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdministracionRecetas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdministracionRecetas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdministracionRecetas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdministracionRecetas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AdministracionRecetas().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBoxTipoProducto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextArea jTestAreaModoPreparacion;
    private javax.swing.JTextField jTextFieldNombreProducto;
    private javax.swing.JTextField jTextFieldPrecio;
    // End of variables declaration//GEN-END:variables
}
